from django import http
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.shortcuts import render
from django.http.response import JsonResponse, HttpResponsePermanentRedirect, HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views import View
from users.forms import UploadImageForm, UserInfoForm, LoginForm, RegisterForm, ForgetForm, ModifyPwdForm
from users.models import UserProfile, EmailVerifyRecord
from utils.email_send import send_register_eamil
from utils.mixin_utils import LoginRequiredMixin


class RegisterView(View):
    # 用户注册
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get('email', None)
            # 如果用户已存在，则提示错误信息
            if UserProfile.objects.filter(email=user_name):
                return render(request, 'register.html', {'register_form': register_form, 'msg': '用户已存在'})

            pass_word = request.POST.get('password', None)
            UserProfile.is_active = False
            # 对保存到数据库的密码加密
            UserProfile.objects.create_user(
                username=user_name,
                password=pass_word,
                email=user_name
            )
            send_register_eamil(UserProfile, 'register')
            return render(request, 'login.html')
        else:
            return render(request, 'register.html', {'register_form': register_form})


class LoginView(View):
    # 用户登录
    def get(self, request):
        # register_form = RegisterForm()
        return render(request, 'login.html')

    def post(self, request):
        # 实例化
        login_form = LoginForm(request.POST)

        if login_form.is_valid() is False:
            return render(request, 'login.html', {'form_errors': login_form.errors})
        # 获取用户提交的用户名和密码
        username = login_form.cleaned_data['username']
        password = login_form.cleaned_data['password']

        user = authenticate(request, username=username, password=password)
        # 如果不是null说明验证成功
        if user is not None:
            # 登录
            login(request, user)
            return render(request, 'index.html')
            # return http.HttpResponse('ok')
        else:
            # return HttpResponsePermanentRedirect(reverse('index'))
            return render(request, 'login.html', {'login_form': login_form})


class ForgetPwdView(View):
    # 忘记密码
    def get(self, request):
        forget_form = ForgetForm
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self, request):
        forget_form = ForgetForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get('email', None)
            send_register_eamil(email, 'forget')
            return render(request, 'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})


class User_infoView(LoginRequiredMixin, View):
    # 用户图像修改
    def post(self, request):
        # 上传的文件都在request.FILES里面获取，所以这里要多传一个这个参数
        image_form = UploadImageForm(request.POST, request.FILES)
        if image_form.is_valid():
            image = image_form.cleaned_data['image']
            request.user.image = image
            request.user.save()
            return HttpResponse('{"status":"success"}', content_type='application/json')
        else:
            return HttpResponse('{"status":"error"}', content_type='application/json')


class LogoutView(View):
    # 用户登出
    def get(self, request):
        logout(request)
        return HttpResponseRedirect(reverse('index'))


class ResetView(View):
    # 修改密码

    def get(self, request, active_code):
        # 验证
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        # 成功获取邮箱 返回修改密码界面
        if all_records:
            for records in all_records:
                email = records.email
                return render(request, 'password_reset.html', {'email': email})
        # 失败 返回错误信息
        return render(request, 'active_fail.html')

    def post(self, request):
        # 修改保存密码
        data = request.POST
        request_from = ModifyPwdForm(data)
        # 验证 如果失败获取错误信息
        res = request_from.is_valid()
        error = request_from.errors
        if res:
            email = data.get('email')
            pwd = request_from.cleaned_data['password1']
            # 对密码进行加密
            user = UserProfile.objects.get(email=email)
            user.password = make_password(pwd, None, 'pbkdf2_sha1')
            user.save()  # 保存数据

            return render(request, 'login.html')
        # 验证失败 返回修改密码界面并 返回错误
        return render(request, 'password_reset.html', {'modify_form': error})


